package com.homework.ch02;


import org.junit.Test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 * @author yuxi
 * @version 1.0
 * @date 2025/11/6
 * @Description:
 */
public class Test03 {
    @Test
    public void truncate() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        BufferedReader br = null;

        try {
            // 1. 获取Druid连接
            conn = JdbcUtils.getConnection();
            // 2. 执行清空表SQL
            String sql = "truncate t_customer";
            pstmt = conn.prepareStatement(sql);
            pstmt.executeUpdate();
            System.out.println("JUnit测试：t_customer表已清空");


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(null, pstmt, conn);
        }

        try {
            // 1. 获取连接+开启事务
            conn = JdbcUtils.getConnection();
            conn.setAutoCommit(false);

            // 读取数据
            String sql1 = "insert into t_customer(id,name, age, birthday) values(?,?,?,?)";
            pstmt = conn.prepareStatement(sql1);
            // 读取文件
            br = new BufferedReader(new InputStreamReader(Test03.class.getClassLoader().getResourceAsStream("customer.txt")));
            String line = null;
            int count = 0;
            while ((line = br.readLine())!= null) {
                String[] data = line.split(":");
                // 向数据库插入数据
                pstmt.setInt(1, Integer.parseInt(data[0]));
                pstmt.setString(2, data[1]);
                pstmt.setInt(3, Integer.parseInt(data[2]));
                pstmt.setString(4, data[3]);
                pstmt.addBatch();
                count++;
                if (count % 3 == 0) {
                    pstmt.executeBatch();
                    System.out.println("已插入" + count + "条数据");
                }
            }
            if (count % 3 != 0) {
                pstmt.executeBatch();
                System.out.println("已插入" + count + "条数据");
            }
            conn.commit();
            System.out.println("数据插入成功,共"+count+"条数据");

        } catch (Exception e) {
            // 7. 异常回滚
            try {
                if (conn != null) conn.rollback();
                System.out.println("JUnit测试：插入失败，事务回滚");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            // 8. 关闭资源
            JdbcUtils.close(null, pstmt, conn);
            try {
                if (br != null) br.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
